/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.visit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.doctor.domain.DoctorInfo;
import com.jeeplus.doctor.service.dto.DoctorInfoDTO;
import com.jeeplus.follow.domain.FollowUpInfo;
import com.jeeplus.follow.service.FollowUpInfoService;
import com.jeeplus.sys.domain.Log;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.visit.service.VisitInfoService;
import com.jeeplus.visit.service.dto.VisitInfoDTO;
import com.jeeplus.visit.service.mapstruct.VisitInfoWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 就诊记录Controller
 * @author xx
 * @version 2023-12-30
 */

@Api(tags ="就诊记录")
@RestController
@RequestMapping(value = "/visit/visitInfo")
public class VisitInfoController {

	@Autowired
	private VisitInfoService visitInfoService;

	@Autowired
	private VisitInfoWrapper visitInfoWrapper;

	@Autowired
	private FollowUpInfoService followUpInfoService;

	/**
	 * 就诊记录列表数据
	 */
	@ApiLog("查询就诊记录列表数据")
	@ApiOperation(value = "查询就诊记录列表数据")
	@PreAuthorize("hasAuthority('visit:visitInfo:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<VisitInfoDTO>> list(VisitInfoDTO visitInfoDTO, Page<VisitInfoDTO> page) throws Exception {
		List<RoleDTO> roleDTOS = UserUtils.getCurrentUserDTO().getRoleDTOList();
		if (!CollectionUtils.isEmpty(roleDTOS)) {
			if (roleDTOS.stream().anyMatch(role -> "patient".equals(role.getEnName()))) {
				visitInfoDTO.setPatientId(UserUtils.getCurrentUserDTO().getId());
			}
		}
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (visitInfoDTO, VisitInfoDTO.class);
		IPage<VisitInfoDTO> result = visitInfoService.findPage (page, queryWrapper);
		return ResponseEntity.ok (result);
	}

	@GetMapping("listAll")
	public ResponseEntity listAll(VisitInfoDTO visitInfoDTO) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (visitInfoDTO, VisitInfoDTO.class);
		List<VisitInfoDTO> visitInfoDTOS = visitInfoService.list(queryWrapper);
		return ResponseEntity.ok (visitInfoDTOS);
	}

	@GetMapping("getMyDoctors")
	public ResponseEntity getMyDoctors(String id){
		System.out.println(id);

		List<DoctorInfoDTO> doctorInfoList = visitInfoService.getMyDoctors(id);

		return ResponseEntity.ok(doctorInfoList);
	}


	/**
	 * 根据Id获取就诊记录数据
	 */
	@ApiLog("根据Id获取就诊记录数据")
	@ApiOperation(value = "根据Id获取就诊记录数据")
	@PreAuthorize("hasAnyAuthority('visit:visitInfo:view','visit:visitInfo:add','visit:visitInfo:edit')")
	@GetMapping("queryById")
	public ResponseEntity<VisitInfoDTO> queryById(String id) {
		return ResponseEntity.ok ( visitInfoService.findById ( id ) );
	}

	/**
	 * 保存就诊记录
	 */
	@ApiLog("保存就诊记录")
	@ApiOperation(value = "保存就诊记录")
	@PreAuthorize("hasAnyAuthority('visit:visitInfo:add','visit:visitInfo:edit')")
	@PostMapping("save")
	public  ResponseEntity <String> save(@Valid @RequestBody VisitInfoDTO visitInfoDTO) {
		//新增或编辑表单保存
		visitInfoService.saveOrUpdate (visitInfoWrapper.toEntity (visitInfoDTO));

		if (visitInfoDTO.getId().isEmpty()){
			//添加满意度调查
			if (visitInfoDTO.getManyiduTime() != null){
				FollowUpInfo followUpInfo = new FollowUpInfo();
				followUpInfo.setFollowName("就诊满意度调查");
				followUpInfo.setPatientId(visitInfoDTO.getPatientId());
				followUpInfo.setDoctorId(visitInfoDTO.getDoctorId());
				followUpInfo.setFollowUpDate(visitInfoDTO.getManyiduTime());
				followUpInfo.setFollowtype("2");
				followUpInfoService.save(followUpInfo);
			}
		}

        return ResponseEntity.ok ( "保存就诊记录成功" );
	}


	/**
	 * 删除就诊记录
	 */
	@ApiLog("删除就诊记录")
	@ApiOperation(value = "删除就诊记录")
	@PreAuthorize("hasAuthority('visit:visitInfo:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        visitInfoService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除就诊记录成功" );
	}
	
	/**
     * 导出就诊记录数据
     *
     * @param visitInfoDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出就诊记录数据")
    @PreAuthorize("hasAnyAuthority('visit:visitInfo:export')")
    @GetMapping("export")
    public void exportFile(VisitInfoDTO visitInfoDTO, Page <VisitInfoDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (visitInfoDTO, VisitInfoDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据
            
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "a.id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List<VisitInfoDTO> result = visitInfoService.findPage ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( visitInfoService, visitInfoWrapper ).exportExcel ( result,  options.getSheetName ( ), VisitInfoDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入就诊记录数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('visit:visitInfo:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( visitInfoService, visitInfoWrapper ).importExcel ( file, VisitInfoDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入就诊记录数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('visit:visitInfo:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "就诊记录数据导入模板.xlsx";
        List<VisitInfoDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( visitInfoService, visitInfoWrapper ).exportExcel ( list,  "就诊记录数据", VisitInfoDTO.class, fileName, null, response );
    }

}
